<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getSiteInfo,
  updateSiteInfo,
  uploadAvatar,
  updateIntroduction,
  uploadBgImage
} from "@/api/blog/site";
import { message } from "@/utils/message";
import ReCropperPreview from "@/components/ReCropperPreview";
import { createFormData, deviceDetection } from "@pureadmin/utils";
import uploadLine from "~icons/ri/upload-line";
import { MdPreview, MdCatalog, MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/preview.css";
import "md-editor-v3/lib/style.css";
const imgSrc = ref("");
const cropperBlob = ref();
const cropRef = ref();
const uploadRef = ref();
const isShow = ref(false);
const imgType = ref("");
const onCropper = ({ blob }) => (cropperBlob.value = blob);

const onChange = uploadFile => {
  console.log("imgType.value:", imgType.value);
  const reader = new FileReader();
  reader.onload = e => {
    imgSrc.value = e.target.result as string;
    isShow.value = true;
  };
  reader.readAsDataURL(uploadFile.raw);
};
// 统一处理不同上传类型
function handleChange(uploadFile, type) {
  imgType.value = type; // 设置当前上传类型
  onChange(uploadFile);
}
const handleClose = () => {
  cropRef.value.hidePopover();
  uploadRef.value.clearFiles();
  isShow.value = false;
};
const handleSubmitImage = () => {
  const blob = cropperBlob.value;
  const file = new File([blob], `avatar_${Date.now()}.png`, {
    type: blob.type || "image/png"
  });
  if (imgType.value === "head") {
    uploadAvatar(file)
      .then(res => {
        if (res) {
          message("更新头像成功", { type: "success" });
          handleClose();
          // 更新页面信息
          fetchSiteInfo();
        } else {
          message("更新头像失败");
        }
      })
      .catch(error => {
        message(`提交异常 ${error}`, { type: "error" });
      });
  } else if (imgType.value === "bgImg") {
    uploadBgImage(file)
      .then(res => {
        if (res) {
          message("更新背景成功", { type: "success" });
          handleClose();
          fetchSiteInfo();
        } else {
          message("更新背景失败");
        }
      })
      .catch(error => {
        message(`提交异常 ${error}`, { type: "error" });
      });
  } else {
    message("请先选择上传类型", { type: "warning" });
  }
};

const userInfoFormRef = ref<FormInstance>();
// 更新信息
const onSubmit = async (formEl: FormInstance) => {
  try {
    // 等待验证成功，否则抛异常
    await formEl.validate();

    // 验证成功，调用接口，记得 await
    await updateSiteInfo(siteInfo.value);
    await fetchSiteInfo();

    message("更新信息成功", { type: "success" });
  } catch (error) {
    // 验证失败或者接口异常都会走这里
    if (error && error.fields) {
      // 是验证失败，打印错误字段
      console.log("error submit!", error.fields);
    } else {
      // 其他异常
      message(`更新失败：${error}`, { type: "error" });
    }
  }
};

const formRef = ref();
const siteInfo = ref({
  id: 0,
  nickname: "",
  avatar: "",
  motto: "",
  bgImage: "",
  giteeUrl: "",
  githubUrl: "",
  title: "",
  headNotice: "",
  sidebarNotice: "",
  icpRecord: "",
  startTime: "",
  lastUpdateTime: "",
  introduction: ""
});

const rules = {
  nickname: [{ required: true, message: "请输入站长昵称", trigger: "blur" }],
  title: [{ required: true, message: "请输入网站标题", trigger: "blur" }]
};

const fetchSiteInfo = async () => {
  const res = await getSiteInfo();
  siteInfo.value = res;
  introduction.value = res.introduction;
};
const isVisible = ref(false);
async function handleUpdate() {
  //提交简历
  console.log("introduction.value: ", introduction.value);
  await updateIntroduction(introduction.value);
  // 更新页面信息
  fetchSiteInfo();
  isVisible.value = false;
}
function openDialog() {
  isVisible.value = true;
}
const introduction = ref("");
onMounted(fetchSiteInfo);
</script>
<template>
  <div>
    <el-row :gutter="20" class="flex justify-center">
      <el-col :span="12">
        <div class="scroll-card">
          <el-card>
            <template #header><h3>站点信息</h3></template>
            <div style="display: flex; justify-content: center">
              <el-form
                ref="userInfoFormRef"
                label-position="top"
                :model="siteInfo"
                :rules="rules"
                style="width: 600px"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item>
                      <el-image
                        style="
                          width: 100px;
                          height: 100px;
                          border-radius: 80px;
                          overflow: hidden;
                        "
                        :src="siteInfo.avatar"
                        fit="cover"
                      />
                      <el-upload
                        ref="uploadRef"
                        accept="image/*"
                        action="#"
                        :limit="1"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="file => handleChange(file, 'head')"
                      >
                        <el-button plain class="ml-4!">
                          <IconifyIconOffline :icon="uploadLine" />
                          <span class="ml-2">更新头像</span>
                        </el-button>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item>
                      <el-image
                        style="
                          width: 120px;
                          height: 100px;
                          border-radius: 12px;
                          overflow: hidden;
                        "
                        :src="siteInfo.bgImage"
                        fit="cover"
                      />
                      <el-upload
                        ref="uploadRef"
                        accept="image/*"
                        action="#"
                        :limit="1"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="file => handleChange(file, 'bgImg')"
                      >
                        <el-button plain class="ml-4!">
                          <IconifyIconOffline :icon="uploadLine" />
                          <span class="ml-2">更新背景图</span>
                        </el-button>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="网站标题" prop="title">
                      <el-input
                        v-model="siteInfo.title"
                        placeholder="请输入网站标题"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="站长昵称" prop="nickname">
                      <el-input
                        v-model="siteInfo.nickname"
                        placeholder="请输入昵称"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="座右铭" prop="motto">
                  <el-input
                    v-model="siteInfo.motto"
                    placeholder="请输入座右铭"
                  />
                </el-form-item>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="Gitee" prop="giteeUrl">
                      <el-input
                        v-model="siteInfo.giteeUrl"
                        placeholder="请输入Gitee链接"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="Github" prop="githubUrl">
                      <el-input
                        v-model="siteInfo.githubUrl"
                        placeholder="请输入Github链接"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="建站时间" prop="startTime">
                      <el-date-picker
                        v-model="siteInfo.startTime"
                        disabled
                        type="datetime"
                        placeholder="Select date and time"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="上次更新时间" prop="lastUpdateTime">
                      <el-date-picker
                        v-model="siteInfo.lastUpdateTime"
                        disabled
                        type="datetime"
                        placeholder="Select date and time"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="顶部通知" prop="headNotice">
                  <el-input
                    v-model="siteInfo.headNotice"
                    placeholder="请输入顶部通知"
                  />
                </el-form-item>
                <el-form-item label="备案信息" prop="icpRecord">
                  <el-input
                    v-model="siteInfo.icpRecord"
                    placeholder="请输入备案信息"
                  />
                </el-form-item>

                <el-form-item label="侧边公告" prop="sidebarNotice">
                  <el-input
                    v-model="siteInfo.sidebarNotice"
                    placeholder="请输入侧边公告"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 3 }"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
                <el-button type="primary" @click="onSubmit(userInfoFormRef)">
                  更新信息
                </el-button>
              </el-form>
              <el-dialog
                v-model="isShow"
                width="40%"
                title="编辑头像"
                destroy-on-close
                :closeOnClickModal="false"
                :before-close="handleClose"
                :fullscreen="deviceDetection()"
              >
                <ReCropperPreview
                  ref="cropRef"
                  :imgSrc="imgSrc"
                  @cropper="onCropper"
                />
                <template #footer>
                  <div class="dialog-footer">
                    <el-button bg text @click="handleClose">取消</el-button>
                    <el-button
                      bg
                      text
                      type="primary"
                      @click="handleSubmitImage"
                    >
                      确定
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="scroll-card">
          <el-card>
            <template #header>
              <div class="card-header">
                <h1 class="title">个人简历</h1>
                <el-button
                  type="primary"
                  class="update-btn"
                  @click="openDialog"
                >
                  更新简历
                </el-button>
              </div>
            </template>
            <!-- 滚动内容区域包裹 MdPreview -->
            <div class="scroll-body">
              <MdPreview
                id="preview-only"
                :modelValue="siteInfo.introduction"
              />
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      v-model="isVisible"
      width="66%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <template #header>
        <div class="card-header">
          <h3 class="title">修改简历</h3>
          <el-button type="primary" class="update-btn" @click="handleUpdate">
            提交更新
          </el-button>
        </div>
      </template>
      <el-card shadow="never" class="card">
        <MdEditor v-model="introduction" />
      </el-card>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.card {
  overflow: hidden;
}
.el-row {
  margin-bottom: 16px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 30px;
}
.scroll-card {
  height: 822px; /* 根据页面布局调整 */
  overflow-y: auto;
}
.card-header {
  position: relative;
  text-align: center;
  padding: 12px 0;
}

.title {
  margin: 0;
  font-weight: bold;
}

.update-btn {
  position: absolute;
  top: 8px;
  right: 12px;
}
</style>
